package com.yami.shop.smsserver.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.yami.shop.common.bean.ALiDaYu;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.util.Json;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.smsserver.SmsServer;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 阿里短信发送接口
 */
@Service
@Slf4j
@AllArgsConstructor
public class AliDayuSmsServerImpl implements SmsServer {


    private ShopConfig shopConfig;

    /**
     * 产品RegionId,开发者无需替换
     */
    private static final String REGION_ID = "cn-hangzhou";

    /**
     * 产品域名,开发者无需替换
     */
    private static final String DOMAIN = "dysmsapi.aliyuncs.com";

    /**
     * 产品version,开发者无需替换
     */
    private static final String VERSION = "2017-05-25";

    /**
     * 产品Action,开发者无需替换
     */
    private static final String ACTION = "SendSms";
    @Override
    public Boolean sendSms(String mobile, String templateCode, Map<String, String> params) {
        ALiDaYu aLiDaYu = shopConfig.getAliDaYu();

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile(REGION_ID, aLiDaYu.getAccessKeyId(), aLiDaYu.getAccessKeySecret());
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(DOMAIN);
        request.setSysVersion(VERSION);
        request.setSysAction(ACTION);
        request.putQueryParameter("RegionId", REGION_ID);
        //必填:待发送手机号
        request.putQueryParameter("PhoneNumbers", mobile);
        //必填:短信签名-可在短信控制台中找到
        request.putQueryParameter("SignName", aLiDaYu.getSignName());
        //必填:短信模板-可在短信控制台中找到
        //获取模板CODE
        templateCode = JSONObject.parseObject(templateCode).getString(Constant.ALIDAYU_CONFIG);
        if(ObjectUtil.isEmpty(templateCode)){
            log.error("该信息没有绑定模板ID");
            return false;
        }
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", Json.toJsonString(params));

        try {
            CommonResponse response = acsClient.getCommonResponse(request);
            log.info(response.getData());
            return true;
        } catch (ClientException e) {
            log.error("发送短信失败，请稍后再试："+e.getMessage());
            return false;
        }
    }
}
